package com.wenwu.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wenwu.common.bean.RoleResources;
import com.wenwu.common.bean.User;
import com.wenwu.common.bean.UserExample;
import com.wenwu.common.exception.RelicsException;
import com.wenwu.common.page.PaginationVO;
import com.wenwu.common.tag.SysConstants;
import com.wenwu.common.utils.MyMd5Utils;
import com.wenwu.dao.RoleResourcesMapper;
import com.wenwu.dao.UserMapper;
import com.wenwu.service.UserService;

/**
 * @project ATHome-Manager-Service
 * @class UserServiceImpl.java
 * @author zhujiagui E-mail:<zhujiagui@zkingsoft.com>
 * @date 2015年2月10日 下午1:09:49
 * @description 用户模块service层实现类
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RoleResourcesMapper roleResourcesMapper;

	public List<User> selectUserList(User user, PaginationVO pageVo)
			throws RelicsException {
		try {
			return userMapper.selectUserList(user, pageVo);
		} catch (SQLException e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public int selectTotalRecord(User user, PaginationVO pageVo)
			throws RelicsException {
		try {
			return userMapper.selectTotalRecord(user, pageVo);
		} catch (SQLException e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public int addUser(User user) throws RelicsException {
		try {
			return userMapper.insertSelective(user);
		} catch (Exception e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public int updateUser(User user) throws RelicsException {
		try {
			return userMapper.updateByPrimaryKey(user);
		} catch (Exception e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public int selectUserByJobNo(String jobno) throws RelicsException {
		try {
			return userMapper.selectUserByJobNo(jobno);
		} catch (SQLException e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public User selectUserByKey(Integer userId) throws RelicsException {
		try {
			return userMapper.selectByPrimaryKey(userId);
		} catch (Exception e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public int deleteUserByKey(List<?> keys) throws RelicsException {
		try {
			return userMapper.deleteUserByKey(keys);
		} catch (SQLException e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public int resetPassword(String newpassword, Integer userId)
			throws RelicsException {
		try {
			return userMapper.resetPassword(newpassword, userId);
		} catch (SQLException e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public int updateUserLock(String locked, Integer userId)
			throws RelicsException {
		try {
			return userMapper.updateUserLock(locked, userId);
		} catch (SQLException e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public User doLogin(User user) throws RelicsException {
		try {
			User u = null;
			String msg = "";
			if (user == null || StringUtils.isBlank(user.getJobNo())) {
				u = new User();
				msg = "请输入正确的用户信息！";
				u.setMsg(msg);
				return u;
			}
			UserExample example = new UserExample();
			example.createCriteria().andJobNoEqualTo(user.getJobNo());
			List<User> ulist = userMapper.selectByExample(example);
			if (ulist == null || ulist.size() < 1) { // 用户不存在
				u = new User();
				msg = "您输入的用户不存在！";
			} else {
				u = ulist.get(0);
				if (u.getIsLocked() != null && u.getIsLocked().equals("1")) { // 用户锁定
					msg = "该用户已锁定";
				} else if (!(u.getPassword()).equals(MyMd5Utils.getMd5Value(
						user.getPassword(), SysConstants.MD5_KEY))) { // 密码错误
					msg = "您输入的密码错误！";
				} else {
					msg = "true"; // 登录成功
				}
			}
			// 登录成功后，获取登录成功后的用户对象属性
			u.setMsg(msg);
			return u;
		} catch (Exception e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public Map<String, List<RoleResources>> getRoleResourceByRoleid(User user)
			throws RelicsException {
		try {
			if (user.getUserName().equals(SysConstants.SUPERMAN)) {// 超级用户不查询
				return null;
			}
			Map<String, List<RoleResources>> roleResMap = null;
			if (user != null && StringUtils.isNotEmpty(user.getRoleId())) {
				List<Integer> ids = new ArrayList<Integer>();
				String[] objs = user.getRoleId().split(",");
				for (String k : objs) {
					ids.add(Integer.valueOf(k));
				}
				List<RoleResources> roleResourcesList = roleResourcesMapper
						.getRoleResourceByRoleid(ids);
				if (roleResourcesList != null) {
					roleResMap = new HashMap<String, List<RoleResources>>();
					for (int i = 0, a = roleResourcesList.size(); i < a; i++) {
						RoleResources rr = roleResourcesList.get(i);
						String sourceid = String.valueOf(rr.getSourceId());
						List<RoleResources> roleResList = null;
						if (roleResMap.containsKey(sourceid)) { // 存在key值
							roleResList = roleResMap.get(sourceid);
						} else {
							roleResList = new ArrayList<RoleResources>();
							roleResMap.put(sourceid, roleResList);
						}
						roleResList.add(rr);
					}
				}
			}
			return roleResMap;
		} catch (SQLException e) {
			throw new RelicsException("系统错误，请稍后再试", e);
		}
	}

	public String updatePwd(User user) throws RelicsException {
		try {
			User u = userMapper.selectByPrimaryKey(user.getUserId());
			if (u == null) { // 用户不存在
				return "01";// 用户不存在
			} else {
				if (!(u.getPassword()).equals(MyMd5Utils.getMd5Value(
						user.getOldpwd(), SysConstants.MD5_KEY))) {
					return "02";// 原始密码错误
				} else {
					userMapper.resetPassword(user.getPassword(),
							user.getUserId());
					return "03";// 密码修改成功
				}
			}
		} catch (Exception e) {
			return "04";// 系统异常
		}
	}
}
